package vip.xiaonuo.common.mq;

import org.noear.folkmq.FolkMQ;
import org.noear.folkmq.client.MqClient;
import org.noear.folkmq.client.MqConsumeHandler;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.io.IOException;
import java.util.Map;

@Configuration
public class EventConfig {

    @Value("${folkmq.server}")
    private String serverUrl;

    @Value("${folkmq.consumerGroup}")
    private String consumerGroup;


    @Autowired  // Spring 会自动注入所有 MqConsumeHandler 类型的 Bean
    private Map<String, MqConsumeHandler> subscriptionMap;

    @Bean
    public MqClient initClient() throws IOException {
        // 构建客户端
        MqClient client = FolkMQ.createClient(serverUrl)
                .nameAs(consumerGroup)
                .connect();

        // 订阅所有 MqConsumeHandler
        for (Map.Entry<String, MqConsumeHandler> subscription : subscriptionMap.entrySet()) {
            client.subscribe(subscription.getKey(), subscription.getValue());
        }

        return client;
    }
}
